<template>
  <div class="beds">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>床位管理</span>
          <div class="header-actions">
            <el-button @click="getBeds" :loading="loading">刷新</el-button>
            <el-button type="primary" @click="openAddModal">新增床位</el-button>
          </div>
        </div>
      </template>
      <div class="search-section">
        <el-input v-model="searchKeyword" placeholder="搜索床位号/房间号/学生" clearable style="width:240px; margin-right:16px;" />
        <el-select v-model="statusFilter" placeholder="全部状态" clearable style="width:120px; margin-right:16px;">
          <el-option label="空闲" value="available" />
          <el-option label="已占用" value="occupied" />
          <el-option label="维修中" value="maintenance" />
        </el-select>
        <el-select v-model="roomFilter" placeholder="全部房间" clearable style="width:120px">
          <el-option v-for="room in rooms" v-if="room" :key="room.id" :label="room.roomNumber || room.number" :value="room.id" />
        </el-select>
      </div>
      <el-table :data="filteredBeds" style="width:100%" v-loading="loading">
        <el-table-column prop="bedNum" label="床位号" width="110" />
        <el-table-column label="房间号" width="110">
          <template #default="{row}">
            <span>{{ getRoomNumber(row.roomId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{row}">
            <el-tag :type="statusTagType(row.status)">{{ statusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入住学生" min-width="130">
          <template #default="{row}">
            <span v-if="row.studentId">{{ row.name }}</span>
            <el-text v-else type="info">未分配</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="checkInDate" label="入住时间" width="130">
          <template #default="{row}">
            <span>{{ formatDate(row.checkInDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200" align="right">
          <template #default="{row}">
            <el-button size="small" @click="viewBed(row)">查看</el-button>
            <el-button size="small" type="primary" @click="openEditModal(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeBed(row)">删除</el-button>
            <el-button v-if="row.status==='occupied'||row.status===1" size="small" @click="checkOut(row)">退房</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑床位弹窗 -->
    <el-dialog v-model="showModal" :title="modalTitle" width="500px">
      <el-form :model="bedForm" label-width="80px">
        <el-form-item label="床位号">
          <el-input v-model="bedForm.bedNum" placeholder="床位号(如1,2,3等)" />
        </el-form-item>
        <el-form-item label="房间号">
          <el-select v-model="bedForm.roomId" placeholder="选择房间" filterable style="width:100%">
            <el-option v-for="room in rooms" v-if="room" :key="room.id" :label="room.roomNumber||room.number" :value="room.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="bedForm.status" placeholder="选择状态" style="width:100%">
            <el-option label="空闲" value="available" />
            <el-option label="已占用" value="occupied" />
            <el-option label="维修中" value="maintenance" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="bedForm.notes" placeholder="备注信息..." :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showModal=false">取消</el-button>
          <el-button type="primary" @click="saveBed">{{ mode==='add'?'添加':'保存' }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { queryRoomBedAPI, addRoomBedAPI, updateRoomBedAPI, deleteRoomBedAPI } from '@/apis/roomBedAPI';
import { queryRoomAPI, queryRoomByIdAPI } from '@/apis/roomAPI';

const beds = ref([]);
const rooms = ref([]);
const loading = ref(false);
const showModal = ref(false);
const mode = ref('add');
const editingBed = ref(null);
const bedForm = ref({ bedNum: '', roomId: '', status: 'available', notes: '', studentId: null });
const searchKeyword = ref('');
const statusFilter = ref('');
const roomFilter = ref('');
const roomNumberCache = ref({});

const getBeds = async () => {
  loading.value = true;
  try {
    const res = await queryRoomBedAPI();
    if (res && res.code === 0 && Array.isArray(res.data)) {
      beds.value = res.data;
    } else {
      ElMessage.error(res?.msg || '获取床位失败');
    }
  } finally {
    loading.value = false;
  }
}
const getRooms = async () => {
  const res = await queryRoomAPI();
  if (res && res.code === 0) rooms.value = (res.data || []).filter(r => !!r && r.id);
}

const getRoomNumber = (roomId) => {
  if (!roomId) return '';
  if (roomNumberCache.value[roomId]) return roomNumberCache.value[roomId];
  const room = rooms.value.find(r => r.id === roomId);
  if (room) {
    roomNumberCache.value[roomId] = room.roomNumber || room.number;
    return roomNumberCache.value[roomId];
  }
  // fallback: 请求接口（此处建议首次加载rooms已包含全部房号，不再请求房间详情）
  return roomId;
};

function statusText(status) {
  if (typeof status === 'number') {
    if (status === 1) return '已占用';
    if (status === 2) return '维修中';
    return '空闲';
  }
  const map = { available: '空闲', occupied: '已占用', maintenance: '维修中' };
  return map[status] || String(status);
}

function statusTagType(status) {
  if (typeof status === 'number') {
    if (status === 1) return 'danger';
    if (status === 2) return 'warning';
    return 'success';
  }
  const map = { available: 'success', occupied: 'danger', maintenance: 'warning' };
  return map[status] || 'info';
}

function formatDate(dateStr) {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN');
}

const filteredBeds = computed(() => {
  let res = beds.value;
  if (searchKeyword.value) {
    const q = searchKeyword.value.toLowerCase();
    res = res.filter(row => String(row.bedNum).toLowerCase().includes(q) || (getRoomNumber(row.roomId)+'').toLowerCase().includes(q) || (row.name||'').toLowerCase().includes(q));
  }
  if (statusFilter.value) {
    res = res.filter(row => row.status === statusFilter.value);
  }
  if (roomFilter.value) {
    res = res.filter(row => row.roomId === roomFilter.value);
  }
  return res;
});

function openAddModal() {
  mode.value = 'add';
  editingBed.value = null;
  bedForm.value = { bedNum: '', roomId: '', status: 'available', notes: '', studentId: null };
  showModal.value = true;
}

function openEditModal(row) {
  mode.value = 'edit';
  editingBed.value = row;
  bedForm.value = { bedNum: row.bedNum, roomId: row.roomId, status: row.status, notes: row.notes||'', studentId: row.studentId||null };
  showModal.value = true;
}

function viewBed(row) {
  ElMessage.info({ message: `床位号: ${row.bedNum}, 房间号: ${getRoomNumber(row.roomId)}, 学生: ${row.name?row.name:'未分配'}` });
}

async function saveBed() {
  try {
    loading.value = true;
    const payload = { ...bedForm.value };
    if (mode.value === 'add') {
      const res = await addRoomBedAPI(payload);
      if (res && res.code === 0) {
        showModal.value = false;
        ElMessage.success('添加成功');
        await getBeds();
      } else {
        ElMessage.error(res?.msg || '添加失败');
      }
    } else if (editingBed.value) {
      payload.id = editingBed.value.id;
      const res = await updateRoomBedAPI(payload);
      if (res && res.code === 0) {
        showModal.value = false;
        ElMessage.success('保存成功');
        await getBeds();
      } else {
        ElMessage.error(res?.msg || '保存失败');
      }
    }
  } finally {
    loading.value = false;
  }
}

async function removeBed(row) {
  try {
    await ElMessageBox.confirm(`确认要删除床位号 ${row.bedNum} 吗?`, '警告', { type:'warning' });
    const res = await deleteRoomBedAPI(row.id);
    if (res && res.code === 0) {
      ElMessage.success('删除成功');
      await getBeds();
    } else {
      ElMessage.error(res?.msg || '删除失败');
    }
  } catch {}
}

async function checkOut(row) {
  try {
    await ElMessageBox.confirm(`确认让学生${row.name||''}退房?`, '操作确认', { type:'warning' });
    const payload = { ...row, status: 'available', studentId: null };
    const res = await updateRoomBedAPI(payload);
    if (res && res.code === 0) {
      ElMessage.success('已退房');
      getBeds();
    } else {
      ElMessage.error(res?.msg || '操作失败');
    }
  } catch {}
}

const modalTitle = computed(() => mode.value==='add' ? '新增床位' : '编辑床位');

onMounted(() => {
  getRooms();
  getBeds();
});
</script>

<style scoped>
.beds { padding:24px; }
.card-header { display:flex; justify-content:space-between; align-items:center; }
.header-actions { display:flex; gap:12px; }
.search-section { margin-bottom:18px; display:flex; gap:16px; align-items:center; }
.dialog-footer { display:flex; justify-content:flex-end; gap:10px; }
@media (max-width:750px) {
  .beds { padding:8px; }
  .search-section { flex-direction:column; align-items:stretch; }
}
</style>